package com.bigtotoro.shuiyincamera;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.DimenUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.umeng.analytics.MobclickAgent;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

public class MyArtListActivity extends BaseActivity {
    private List<MyArt> mPhotoList = new ArrayList<>();
    private RecyclerView recyclerView;
    private ImageView iv_empty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_art_list);
        iv_empty = findViewById(R.id.iv_empty);
        iv_empty.setVisibility(View.GONE);
        initBase();
        initGrid();
        initData();
    }

    private BaseQuickAdapter mAdapter ;
    private void initGrid() {
        recyclerView = findViewById(R.id.recycler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MyArtListActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(MyArtListActivity.this, LinearLayoutManager.HORIZONTAL, DimenUtils.dip2px(MyArtListActivity.this, 1), Color.parseColor("#eeeeee")));
        mAdapter = new BaseQuickAdapter<MyArt, BaseViewHolder>(
                R.layout.item_grid, mPhotoList){
            @Override
            protected void convert(BaseViewHolder helper, MyArt item) {
                helper.setText(R.id.item_time, "最后修改时间: " + item.getCreate_time())
                        .setText(R.id.item_path, "文件路径: " + item.getPath())
                        .addOnClickListener(R.id.iv_photo);
                ImageView iv_photo = helper.getView(R.id.iv_photo);
                if (item.getType() == 2){
                    iv_photo.setImageResource(R.mipmap.iv_audio);
                }else {
                    if (item.getPath() != null && item.getPath().lastIndexOf(".") > 0) {
                        Glide.with(MyArtListActivity.this).load(new File(item.getPath())).into(iv_photo);
                    }
                }

                ImageView iv_cover = helper.getView(R.id.iv_cover);
                switch (item.getType()){  //根据类型显示不同的标签
                    case 0: //图片
                        iv_cover.setImageDrawable(getResources().getDrawable(R.mipmap.type_img));
                        break;
                    case 1: //视频
                        iv_cover.setImageDrawable(getResources().getDrawable(R.mipmap.type_video));
                        break;
                    case 2: //音频
                        iv_cover.setImageDrawable(getResources().getDrawable(R.mipmap.type_audio));
                        break;
                }
            }
        };
        recyclerView.setAdapter(mAdapter);
        recyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //根据当前选中图片还是视频，分别跳转
                MyArt art = mPhotoList.get(position);
                if (art!=null && art.getType()==0){  //图片预览

                    startActivityForResult(new Intent(MyArtListActivity.this,
                            ShowMyArtsActivity.class)
                            .putExtra(EXTRA_OUTPUT, art.getPath())
                            .putExtra("create_time", art.getTrueCreateTime())
                            .putExtra("position",  position)
                            .putExtra("width",  art.getWidth())
                            .putExtra("height", art.getHeight())
                            .putExtra("mode", "myartlist")
                            .putExtra("type", "0"),REQUEST_CODE_SHOW_IMAGE);

                }else if (art!=null && art.getType()==1){  //视频预览
                    startActivityForResult(new Intent(MyArtListActivity.this,
                            ShowMyArtsActivity.class)
                            .putExtra(EXTRA_OUTPUT, art.getPath())
                            .putExtra("create_time", art.getTrueCreateTime())
                            .putExtra("position",  position)
                            .putExtra("width",  art.getWidth())
                            .putExtra("height", art.getHeight())
                            .putExtra("mode", "myartlist")
                            .putExtra("type", "1"),REQUEST_CODE_SHOW_VIDEO);
                }else if (art!=null && art.getType()==2){  //音频预览
                    startActivityForResult(new Intent(MyArtListActivity.this,
                            ShowMyArtsActivity.class)
                            .putExtra(EXTRA_OUTPUT, art.getPath())
                            .putExtra("create_time", art.getTrueCreateTime())
                            .putExtra("position",  position)
                            .putExtra("width",  art.getWidth())
                            .putExtra("height", art.getHeight())
                            .putExtra("mode", "myartlist")
                            .putExtra("type", "2"),REQUEST_CODE_SHOW_AUDIO);

                }

            }
        });
    }

    private static final int REQUEST_CODE_SHOW_IMAGE = 9003;
    private static final int REQUEST_CODE_SHOW_VIDEO = 9004;
    private static final int REQUEST_CODE_SHOW_AUDIO = 9005;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK){
            if (requestCode == REQUEST_CODE_SHOW_IMAGE){
                //如果点击了删除
                if (data!=null && data.getIntExtra("position",-1)!= -1){
                    int position = data.getIntExtra("position",-1);
                    //删除这条数据
                    deleteFromLitepal(position);
                }
            }else if (requestCode == REQUEST_CODE_SHOW_VIDEO){
                //如果点击了删除
                if (data!=null && data.getIntExtra("position",-1)!= -1){
                    int position = data.getIntExtra("position",-1);
                    //删除这条数据
                    deleteFromLitepal(position);

                }
            }else if (requestCode == REQUEST_CODE_SHOW_AUDIO){
                //如果点击了删除
                if (data!=null && data.getIntExtra("position",-1)!= -1){
                    int position = data.getIntExtra("position",-1);
                    //删除这条数据
                    deleteFromLitepal(position);
                }
            }
        }
    }


    private void deleteFromLitepal(int position) {
        MyArt art = mPhotoList.get(position);
        LitePal.deleteAll(MyArt.class, "create_time =?", art.getTrueCreateTime());
        initData();
        Toast.makeText(this, "作品已删除", Toast.LENGTH_SHORT).show();
    }

    private void openAssignFolder(String path) {
        File file = new File(path);
        if (null == file || !file.exists()) {
            return;
        }
        //获取父目录  
        File parentFlie=new File(file.getParent());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.fromFile(new File(parentFlie.getPath())));
//        intent.putExtra("org.openintents.extra.ABSOLUTE_PATH", folder.path);
        if (intent.resolveActivity(MyArtListActivity.this.getPackageManager()) != null) {
            startActivity(intent);
        }
    }

    private void initData() {
        //应该按时间倒序排列
        List<MyArt> list = LitePal.order("create_time desc").find(MyArt.class);
        if (list != null) {
            mPhotoList.clear();
            mPhotoList.addAll(list);
            if (mAdapter!=null){
                mAdapter.notifyDataSetChanged();
            }
            if (list!=null && list.size()>0){
                iv_empty.setVisibility(View.GONE);
            }else {
                iv_empty.setVisibility(View.VISIBLE);
            }

        } else {
            Toast.makeText(MyArtListActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
            iv_empty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MyArtListActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MyArtListActivity");//统计页面
        MobclickAgent.onPause(this);
    }
}
